package com.snail.sell.controller;


import com.snail.sell.dataobject.ProductCategory;
import com.snail.sell.dataobject.ProductInfo;
import com.snail.sell.service.CategoryService;
import com.snail.sell.service.ProductService;
import com.snail.sell.utils.ResultVOUtils;
import com.snail.sell.vo.ProductInfoVO;
import com.snail.sell.vo.ProductVO;
import com.snail.sell.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 11:14 2017/12/3
 * @Modified By:
 **/
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("list")
    @Cacheable(cacheNames = "order11",key = "123",condition = "#productid.length()>3",unless = "#result.getCode()!=0")
    public ResultVO list(){

        List<ProductInfo> productInfoList = productService.findUpAll();

        List<Integer> categoryTypeList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());

        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
        //前台商品（包含类目）列表
        List<ProductVO> productVOList = new ArrayList<>();

        for (ProductCategory productCategory:productCategoryList){
            //前台商品
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            /*productVO.setProductInfoVOList(productInfoVOList);*/
            //前台商品详细信息列表
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo: productInfoList) {
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    //前台商品详细信息
                    ProductInfoVO productInfoVO = new ProductInfoVO();

                    BeanUtils.copyProperties(productInfo,productInfoVO);
                   //productInfoVOList添加前台商品详细信息ProductInfoVO
                    productInfoVOList.add(productInfoVO);
                }
                //为前台商品属性ProductInfoVOList赋值
               productVO.setProductInfoVOList(productInfoVOList);

            }
            productVOList.add(productVO);
        }

        return ResultVOUtils.success(productVOList);
    }
}
